package com.xianrenit.xianrenpuzi.cart.service.impl;

import com.xianrenit.xianrenpuzi.cart.service.CartService;
import com.xianrenit.xianrenpuzi.common.handler.exception.SpzxException;
import com.xianrenit.xianrenpuzi.common.handler.interceptor.SpzxServiceAuthInterceptor;
import com.xianrenit.xianrenpuzi.model.entity.h5.CartInfo;
import com.xianrenit.xianrenpuzi.model.entity.h5.UserInfo;
import com.xianrenit.xianrenpuzi.model.entity.product.ProductSku;
import com.xianrenit.xianrenpuzi.model.result.Result;
import com.xianrenit.xianrenpuzi.model.result.ResultCodeEnum;
import com.xianrenit.xianrenpuzi.service.product.client.ProductClient;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    ProductClient productClient;
    private BoundHashOperations getUserCart(){
        UserInfo userInfo = SpzxServiceAuthInterceptor.THREAD_LOCAL.get();
        BoundHashOperations ops = redisTemplate.boundHashOps("spzx:cart:" + userInfo.getId());
        return ops;
    }
    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        //1、获取当前用户的购物车:购物车使用redis的hash结构
        UserInfo userInfo = SpzxServiceAuthInterceptor.THREAD_LOCAL.get();
        BoundHashOperations ops = redisTemplate.boundHashOps("spzx:cart:" + userInfo.getId());
        //ops就是 当前用户的购物车
        //2、如果购物车中存在skuId对应的购物项：更新数据加上skuNum
        Boolean flag = ops.hasKey(skuId.toString());//使用字符串当做键
        //获取skuId映射的购物项对象
        CartInfo cartInfo = null;
        if(flag){
            cartInfo = (CartInfo) ops.get(skuId.toString());
            //修改数量
            cartInfo.setSkuNum(cartInfo.getSkuNum()+skuNum);
            cartInfo.setUpdateTime(new Date());

        }else{
            //3、如果不存在skuId的购物项，新创建购物项存到购物车中
            //新创建购物项
            cartInfo = new CartInfo();
            cartInfo.setSkuId(skuId);
            cartInfo.setSkuNum(skuNum);
            cartInfo.setUserId(userInfo.getId());
            cartInfo.setCreateTime(new Date());
            cartInfo.setUpdateTime(new Date());
            cartInfo.setIsChecked(1);//新增的购物项 默认设置选中
            //需要查询sku表获取属性值
            Result<ProductSku> result = productClient.getById(skuId);
            if(result.getCode()!=200){
                //远程调用失败
                throw new SpzxException(ResultCodeEnum.FAIL,null);
            }
            ProductSku productSku = result.getData();
            //根据skuId查询sku详情
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setImgUrl(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
        }
        //更新到redis中: 相同的键 后设置的值会覆盖之前的
        //存到购物车中
        ops.put(skuId.toString() , cartInfo);

    }

    @Override
    public List<CartInfo> cartList() {
        //1、获取购物车
        BoundHashOperations userCart = getUserCart();
        //2、返回购物车的所有购物项List集合
        return userCart.values();
    }

    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        BoundHashOperations userCart = getUserCart();
        //必须使用字符串才能查询到购物项
        CartInfo cartInfo = (CartInfo) userCart.get(skuId.toString());
        cartInfo.setIsChecked(isChecked);
        userCart.put(skuId.toString(),cartInfo);
    }

    @Override
    public void deleteCartBySkuId(Long skuId) {
        BoundHashOperations userCart = getUserCart();
        userCart.delete(skuId.toString());
    }

    @Override
    public void clearCart() {
        UserInfo userInfo = SpzxServiceAuthInterceptor.THREAD_LOCAL.get();
        redisTemplate.delete("spzx:cart:" + userInfo.getId());
    }

    @Override
    public void allCheckCart(Integer isChecked) {
        BoundHashOperations userCart = getUserCart();
        if(userCart.size()==0){
            return;
        }
        userCart.entries().forEach((skuIdStr , cartInfo)->{
           CartInfo ci = (CartInfo) cartInfo;
           ci.setIsChecked(isChecked);
           userCart.put(skuIdStr,ci);
        });
    }

    @Override
    public List<CartInfo> checkedCartInfos() {
        //泛型1：redis键类型， 泛型2：hash的key类型  泛型3 hash的value的类型
        BoundHashOperations<String,String,CartInfo> userCart = getUserCart();
        return userCart.values().stream()
                .filter(cartInfo->cartInfo.getIsChecked()==1)
                .collect(Collectors.toList());
    }

    @Override
    public void delCheckedCartInfos() {
        BoundHashOperations<String,String,CartInfo> userCart = getUserCart();
        userCart.entries().forEach((skuIdStr , cartInfo)->{
            if(cartInfo.getIsChecked().intValue() == 1){
                userCart.delete(skuIdStr);
            }
        });
    }
}
